
<!DOCTYPE html>
<html>
	<head>
		<title>商品表-添加/修改</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!-- 所有的 css js 资源 -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css">
		<link rel="stylesheet" href="../../static/sa.css"> 
		<script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>
		<script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script>
		<script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js"></script>
		<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
		<script src="../../static/sa.js"></script>
		<script src="../../static/kj/upload-util.js"></script>
		<script src="../../static/kj/wangEditor.up.js"></script>
		<!-- 为了抹平sa-admin和sa-plus之间差异的补充 -->
		<link rel="stylesheet" href="./sa-plus-sa.css">
		<style type="text/css">
			.c-panel .el-form .c-label{width: 7em !important;}
			.c-panel .el-form .el-input, .c-panel .el-form .el-textarea__inner{width: 250px;}
			/*  普通文本和富文本一起变长  */
			.c-panel .el-form .el-input, .c-panel .el-form .el-textarea__inner{width: 700px;}
			.c-item-mline{width: 700px;}
			.el-table__body-wrapper{min-height: 0px;}
			
			
			/* .c-item .image-box{padding-bottom: -20px;} */
			.el-select__tags-text{color: #1890FF; }
			.sk-fox{border: 1px #eee solid; padding: 5px 14px; margin-top: 8px;}
			.sk-name{font-weight: bold;}
			/* 规格值 */
			.sku-box .el-tag{border-radius: 1px; margin-right: 5px;}
			/* .sku-box .el-input-group__append{padding: 0 10px;} */
			.sku-box .el-input-group__prepend,.sku-box .el-input-group__append{padding: 0 10px; border-radius: 1px !important; color: #666;}
			.not-values-tips{color: #aaa; margin-right: 14px;}
			.del-r{margin-left: 10px; }
			.sv-name{/* white-space: nowrap; *//* word-break:keep-all; */ }
			.svgao{color: #409EFF; font-weight: bold;}
			.small-input{width: 85px !important;}
			
		</style>
	</head>
	<body>
		<div class="vue-box" :class="{sbot: id}" style="display: none;" :style="'display: block;'">
			<!-- ------- 内容部分 ------- -->
			<div class="s-body">
				<div class="c-panel">
					<div class="c-title">商品添加</div>
					<el-form size="mini" v-if="m">
						<!-- no字段： m.id - 记录id -->
						<div class="c-item br">
							<label class="c-label">商品名称：</label>
							<el-input size="mini" v-model="m.name" placeholder="请输入商品名称"></el-input>
						</div>
						<div class="c-item br">
							<label class="c-label">所属分类：</label>
							<el-select size="mini" v-model="m.type_id" placeholder="请选择一个分类">
								<el-option label="请选择" :value="0" disabled></el-option>
								<el-option v-for="item in sysTypeList" :label="item.name" :value="item.id" :key="item.id"></el-option>
							</el-select>
						</div>
						<div class="c-item br">
							<label class="c-label" style="vertical-align: top;">商品头像：</label>
							<img :src="m.avatar" style="width: 3em; height: 3em; cursor: pointer;" 
								@click="sa.showImage(m.avatar, '400px', '400px')" v-if="!sa.isNull(m.avatar)">
							<el-link type="primary" @click="sa.uploadImage(src => {m.avatar = src; sa.ok2('上传成功');})">上传</el-link>
						</div>
						<div class="c-item br">
							<label class="c-label" style="vertical-align: top;">轮播图片：</label>
							<div class="c-item-mline image-box">
								<div class="image-box-2" v-for="item in m.image_list_arr">
									<img :src="item" @click="sa.showImage(item, '500px', '400px')" />
									<p>
										<i class="el-icon-close" style="position: relative; top: 2px;"></i>
										<el-link @click="sa.arrayDelete(m.image_list_arr, item)" style="color: #999;">删除这张 </el-link>
									</p>
								</div>
								<!-- 上传图集 -->
								<div class="image-box-2 up_img" @click="sa.uploadImageList(src => m.image_list_arr.push(src))">
									<img src="../../static/img/up-icon.png">
								</div>
							</div>
						</div>
						<div class="c-item br">
							<label class="c-label">商品标签：</label>
							<!-- <span v-for="item in m.label_list_arr">
								<el-tag size="medium" closable @close="sa.arrayDelete(m.label_list_arr, item)">{{item}}</el-tag>
							</span> -->
							<el-select
								size="small"
							    v-model="m.label_list_arr"
							    multiple
							    filterable
							    allow-create
							    default-first-option
							    placeholder="请选择商品标签">
							    <el-option v-for="item in labelList" :key="item" :label="item" :value="item"></el-option>
							  </el-select>
						</div>
						<div class="c-item br">
							<label class="c-label">商品价格：</label>
							<el-input size="mini" v-model="m.price" type="number" placeholder="请输入商品价格"></el-input>
						</div>
						<div class="c-item br">
							<label class="c-label">商品运费：</label>
							<el-input size="mini" v-model="m.freight" type="number" placeholder="请输入商品运费"></el-input>
						</div>
						<div class="c-item br">
							<label class="c-label">商品库存：</label>
							<el-input size="mini" v-model="m.stock_count" type="number" placeholder="请输入商品库存"></el-input>
						</div>
						<!-- ----------------- 规格值设置 ------------------- -->
						<div class="c-item br sku-box">
							<label class="c-label" style="vertical-align: top;">商品规格：</label>
							<div class="c-item-mline">
								<!-- 规格名称 -->
								<el-input size="mini" v-model="specKeyAddText" style="width: 400px;" placeholder="例如: 颜色、大小" 
									@keyup.enter.native="specKeyAdd(specKeyAddText)">
									<template slot="prepend">规格组：</template>
								</el-input>
								<el-button size="mini" type="primary" icon="el-icon-plus" @click="specKeyAdd(specKeyAddText)">添加</el-button>
								<!-- 规格值 循环出来 -->
								<div class="sk-fox" v-for="sk in specKeyList">
									<div class="sk-name">
										<span>{{sk.name}}</span>
										<el-link type="info" class="del-r" @click="sa.arrayDelete(specKeyList, sk); f5Spec()">
											<i class="el-icon-close"></i>
											<small style="vertical-align: top;">删除</small>
										</el-link>
									</div>
									<div class="sv-box">
										<!-- <div class="sv-box"></div> -->
										<span v-for="sv in sk.values">
											<el-tag size="medium" closable effect="plain" @close="sa.arrayDelete(sk.values, sv); f5Spec()">{{sv}}</el-tag>
										</span>
										<span class="not-values-tips" v-if="sk.values.length == 0">(请添加)</span>
										<el-input size="mini" style="width: 150px;" v-model="sk.specValueAddText" 
											@keyup.enter.native="specValueAdd(sk, sk.specValueAddText)">
											<el-button slot="append" @click="specValueAdd(sk, sk.specValueAddText)">添加</el-button>
										</el-input>
									</div>
								</div>
								<div class="not-values-tips" v-if="specKeyList.length == 0" style="margin-top: 14px;">
									<span>(请添加规格组)</span>
									<el-link style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="addDefaultSpec()" v-if="specKeyList.length == 0">添加默认规格</el-link>
								</div>
								
							</div>
						</div>
						<!-- ----------------- 规格列表 ------------------- -->
						<div class="c-item br">
							<label class="c-label" style="vertical-align: top;">详细设置：</label>
							<div class="c-item-mline" >
								<el-table :data="specList" size="small" border>
									<!-- <el-table-column type="selection" width="45px"></el-table-column> -->
									<!-- <el-table-column label="id" prop="id" ></el-table-column> -->
									<el-table-column label="参数">
										<template slot-scope="s"><div class="sv-name" :class="{svgao: s.row.status==1}">{{s.row.name}}</div></template>
									</el-table-column>
									<el-table-column label="图标" width="100px">
										<template slot-scope="s">
											<img :src="s.row.avatar" @click="sa.showImage(s.row.avatar, '400px', '400px')" v-if="s.row.avatar" 
												style="width: 3em; height: 3em; border-radius: 3px; cursor: pointer; vertical-align: middle;" />
											<!-- <span v-else>无</span> -->
											<el-link type="info" @click="s.row.avatar = ''" :disabled="s.row.status==2" v-if="s.row.avatar">删除</el-link>
											<el-link type="primary" @click="sa.uploadImage(src => {s.row.avatar = src; sa.ok2('上传成功');})" :disabled="s.row.status==2" v-else>上传</el-link>
										</template>
									</el-table-column>
									<el-table-column label="库存" width="150px">
										<template slot-scope="s">
											<el-input class="small-input" size="mini" v-model="s.row.stock_count" type="number" :disabled="s.row.status==2"></el-input>
											<span>件</span>
										</template>
									</el-table-column>
									<el-table-column label="价格" width="150px" >
										<template slot-scope="s">
											<el-input class="small-input" size="mini" v-model="s.row.price" type="number" :disabled="s.row.status==2"></el-input>
											<span>元</span>
										</template>
									</el-table-column>
									<el-table-column label="上下架" width="120px">
										<template slot-scope="s">
											<el-switch v-model="s.row.status" :active-value="1" :inactive-value="2" inactive-color="#ccc"></el-switch>
											<span style="color: #999; position: relative; top: 2px;">
												<span v-if="s.row.status==1">上架</span>
												<span v-else>下架</span>
											</span>
											<!-- <el-button class="c-btn" type="success" icon="el-icon-view" @click="get(s.row)">查看</el-button>
											<el-button class="c-btn" type="primary" icon="el-icon-edit" @click="update(s.row)">修改</el-button>
											<el-button class="c-btn" type="danger" icon="el-icon-delete" @click="del(s.row)">删除</el-button> -->
										</template>
									</el-table-column>
									<!-- {name: '红色 4.7寸 64G', avatar: '', price: 19.99, stock_count: 9999}, -->
								</el-table>
							</div>
						</div>
						<!-- ----------------- 富文本 ------------------- -->
						<div class="c-item br editor-item" style="margin-top: 10px;">
							<label class="c-label">图文介绍：</label>
							<div class="editor-box">
								<div id="editor"></div>
							</div>
						</div>
						<div style="clear: both;"></div>
						<div class="c-item br">
							<label class="c-label">商品状态：</label>
							<el-radio-group v-model="m.status" size="mini">
								<el-radio-button :label="1">上架</el-radio-button>
								<el-radio-button :label="2">下架</el-radio-button>
							</el-radio-group>
						</div>
						<!-- date-create字段： m.create_time - 创建日期 -->
						<!-- date-update字段： m.update_time - 更新日期 -->
						<div class="c-item br s-ok">
							<label class="c-label"></label>
							<el-button size="mini" type="primary" icon="el-icon-plus" @click="ok()">保存</el-button>
						</div>
					</el-form>
				</div>
			</div>
			<!-- ------- 底部按钮 ------- -->
			<div class="s-foot">
				<el-button size="mini" type="primary" @click="ok()">确定</el-button>
				<el-button size="mini" @click="sa.closeCurrIframe()">取消</el-button>
			</div>
		</div>
		<script>
			// 创建编辑器
			function create_editor(content) {
				var E = window.wangEditor;
				window.editor = new E('#editor');

				editor.customConfig.menus = [
					'head', 'fontSize', 'fontName', 'italic', 'underline', 'strikeThrough', 'foreColor', 'backColor', 'link', 'list',
					'justify', 'quote', 'emoticon', 'image', 'table', 'code', 'undo', 'redo' // 重复
				]
				editor.customConfig.debug = true; // debug模式
				// editor.customConfig.uploadFileName = 'file'; // 图片流name
				editor.customConfig.withCredentials = true; // 跨域携带cookie
				editor.customConfig.uploadImgMaxSize = 100 * 1024 * 1024;	// 图片大小最大100M
				// editor.customConfig.uploadImgShowBase64 = true   	// 使用 base64 保存图片
				// 重写上传图片的函数到OSS 
				editor.customConfig.customUploadImg = function(files, insert) {
					var file = files[0]; // 文件对象 
					startUploadImage2(file, function(src) {
						insert(src);
						sa.msg('上传成功');
					});
				}
				editor.create(); // 创建
				editor.txt.html(content);	// 为编辑器赋值
				setTimeout(function() {
					$('.editor-box').height($('.editor-box').height());
				})
			}
		</script>
        <script>
			
			var app = new Vue({
				el: '.vue-box',
				data: {
					id: sa.p('id', 0),		// 获取超链接中的id参数（0=添加，非0=修改） 
					m: null,		// 实体对象 
					sysTypeList: [		// 所有分类列表
						{id: 101, name: '虚拟物品'},
						{id: 102, name: '休闲零食'},
						{id: 103, name: '服饰箱包'},
						{id: 104, name: '电脑办公'},
					],		
					labelList: ['免配送费', '九折优惠', '全面保修', '顺丰包邮', '假一赔四', '七天无理由', '退货无忧']	,// 可选的商品标签
					specKeyAddText: '',
					// 规格可选值列表 
					specKeyList: [
						// {name: '颜色', specValueAddText: '', values: ['红色', '蓝色', '绿色']},
						// {name: '屏幕', specValueAddText: '', values: ['4.3寸', '4.7寸', '5.0寸']},
						// {name: '内存', specValueAddText: '', values: ['16G', '32G', '64G']},
					],
					// 规格列表
					specList: [
						// name=规格值, avatar=图标, price=价格, stock_count=库存, status=状态(1=上架, 2=下架)
						// {name: '红色 4.7寸 64G', avatar: '', price: 19.99, stock_count: 9999, status: 1},
						// {name: '红色 4.7寸 64G', avatar: '', price: 19.99, stock_count: 9999, status: 1},
						// {name: '红色 4.7寸 64G', avatar: '', price: 19.99, stock_count: 9999, status: 1},
					]
				},
				methods: {
					// 添加一个规格名称
					specKeyAdd: function(text) {
						text = text || this.specKeyAddText;
						if(text == null || text == '') {
							return;
						}
						if(this.specKeyList.indexOf(text) > -1) {
							return sa.error2('已经有这个规格了');
						}
						var sk = {name: text.replace(/\s/g,""), specValueAddText: '', values: []};
						this.specKeyList.push(sk); 
						this.specKeyAddText='';
						this.f5Spec();
					},
					// 添加一个规格值
					specValueAdd: function(sk, text) {
						text = text || sk.specValueAddText;
						if(text == null || text == '') {
							return;
						}
						if(sk.values.indexOf(text) > -1) {
							return sa.error2('已经有这个规格值了');
						}
						var value = text.replace(/\s/g,"");
						sk.values.push(value); 
						sk.specValueAddText='';
						this.f5Spec();
					},
					// 刷新spec
					f5Spec: function() {
						// 获取总数组 
						var arrAll = [];
						this.specKeyList.forEach(function(sk) {
							if(sk.values.length > 0) {
								arrAll.push(sk.values);
							}
						})
						// 创建递归函数，计算笛卡尔积
						var list = [];
						if(arrAll.length == 0) {
							
						} else if(arrAll.length == 1) {
							list = arrAll[0];
						} else {
							function cartesian(arr1, arr2, index) {
							    if (index < arrAll.length) {
							        var result = [];
							        var i;
							        for (i = 0; i < arr1.length; i++) {
							            var j;
							            for (j = 0; j < arr2.length; j++) {
							                result.push(arr1[i] + ' ' + arr2[j]);//把数组的元素组合成一个新的元素，如果是对象
							            }
							        }
							        list=result;
							        // console.log(index, result);
							        cartesian(result, arrAll[index + 1], index + 1);
							    }
							}
							cartesian(arrAll[0], arrAll[1], 1);
						}
						// 将笛卡尔积转换为spec数组
						var specList = [];
						for (var i = 0; i < list.length; i++) {
							var spec = {
								name: list[i], 
								avatar: '',
								price: '0',
								stock_count: '0',
								status: 1
							}
							// 如果已经有值，则直接赋上 
							var spec_old = this.specList[i];
							console.log(spec_old);
							if(spec_old) {
								spec.avatar = spec_old.avatar;
								spec.price = spec_old.price;
								spec.stock_count = spec_old.stock_count;
								spec.status = spec_old.status;
							}
							specList.push(spec);
						}
						// 赋值到vue属性上 
						this.specList = specList;
					},
					// 一键添加默认规格
					addDefaultSpec: function() {
						this.specKeyAdd('规格');
						console.log(this.specKeyList[0]);
						this.specValueAdd(this.specKeyList[0], '默认');
					},
					// 创建一个 默认Model 
					createModel: function() {
						return {
							id: 0,		// 记录id 
							name: '',		// 商品名称 
							type_id: '',		// 所属分类 
							avatar: '',		// 商品头像 
							image_list: '',		// 轮播图片 
							image_list_arr: [],		// 轮播图片 - 转数组
							price: '',		// 商品价格 
							freight: '',	// 运费 
							stock_count: '',		// 剩余库存 
							content: '',		// 图文介绍 
							status: 1,		// 商品状态 (1=上架,2=下架) 
							label_list: '',		// 标签列表 
							spec_key_list_str: '[]',	// 规格列表(字符串形式)
							// create_time: '',		// 创建日期 
							// update_time: '',		// 更新日期 
						}
					},
					// 写入商品对象 
					initModel: function(m) {
						// 轮播图
						m.image_list_arr = sa.isNull(m.image_list) ? [] : res.data.image_list.split(',');		// 轮播图片 字符串转数组 
						// 标签列表
						m.label_list_arr = sa.isNull(m.label_list) ? [] : res.data.label_list.split(',');	// 字符串转数组 
						// 规格值 
						this.specKeyList = sa.JSONParse(m.spec_key_list_str);
						// 赋值
						this.m = m;
						// 初始化富文本
						this.$nextTick(function() {
							create_editor(m.content);
						})
					},
					// 表单验证
					submitCheck: function() {
						try{
							var m = this.m;		// 获取 m对象 
							// sa.checkNull(m.id, '请输入记录id');
							sa.checkNull(m.name, '请输入商品名称');
							sa.checkNull(m.type_id, '请输入所属分类');
							sa.checkNull(m.avatar, '请输入商品头像');
							sa.checkNull(m.image_list, '请输入轮播图片');
							sa.checkNull(m.price, '请输入商品价格');
							sa.checkNull(m.freight, '请输入商品运费');
							sa.checkNull(m.stock_count, '请输入剩余库存');
							sa.checkNull(m.content, '请输入图文介绍');
							sa.checkNull(m.status, '请输入商品状态');
							sa.check(this.specList.length == 0, '请至少添加一个规格');
							// sa.checkNull(m.create_time, '请输入创建日期');
							// sa.checkNull(m.update_time, '请输入更新日期');
							return 'ok';	// 全部通过验证，返回ok 表示正确 
						} catch(e) {
							sa.error(e);
						}
					},
					// 提交数据 
					ok: function(){
						// 验证 
						var m = this.m;
						m.image_list = m.image_list_arr.join(',');	// 图片 数组转字符串 
						m.label_list = m.label_list_arr.join(',');	// 标签 数组转字符串 
						m.spec_key_list_str = JSON.stringify(this.specKeyList);	// 规格key数据 对象转字符串 
						m.spec_list_str = JSON.stringify(this.specList);	// 规格列表数据 对象转字符串 
						m.content = editor.txt.html();	// 获取富文本值 
						if(this.submitCheck() != 'ok') {
							return;
						}
						// 开始增加或修改
						m.create_time = undefined;		// 不提交属性：创建日期
						m.update_time = undefined;		// 不提交属性：更新日期
						if(this.id <= 0) {	// 添加
							sa.ajax2('/SerGoods/add', m, function(res){
								sa.alert('增加成功', this.clean); 
							}.bind(this));
						} else {	// 修改
							sa.ajax2('/SerGoods/update', m, function(res){
								sa.alert('修改成功', this.clean);
							}.bind(this));
						}
					},
					// 添加/修改 完成后的动作
					clean: function() {
						if(this.id == 0) {
							console.log('数据为：', this.m);
							layer.alert(JSON.stringify(this.m), {title: '数据为：'});
							// 打开下面的注释，可直接在添加成功后，清空数据 
							// this.m = this.createModel();
							// this.$nextTick(function() {
							// 	create_editor('');	// 清空富文本
							// 	this.specKeyList = [];
							// 	this.f5Spec();
							// }.bind(this))
						} else {
							parent.app.f5();		// 刷新父页面列表
							sa.closeCurrIframe();	// 关闭本页 
						}
					},
					
				},
				mounted: function(){
					// 初始化数据 
					if(this.id <= 0) {	
						this.initModel(this.createModel());
					} else {	
						sa.ajax2('/SerGoods/getById?id=' + this.id, function(res) {
							this.initModel(res.data);
							// 加载规格列表 (默认为空) 
							this.specList = [];
						}.bind(this))
					}
				
				}
			})
			
		</script>
	</body>
</html>